      1  import java.awt.BorderLayout;

      2  import java.awt.Color;

      3  import java.awt.GridLayout;

      4  import javax.swing.JFrame;

      5  import javax.swing.JLabel;

      6  import javax.swing.JPanel;

      7  import javax.swing.JSlider;

      8  import javax.swing.event.ChangeListener;

      9  import javax.swing.event.ChangeEvent;

     10

     11  public class ColorFrame extends JFrame

     12  {

     13     private static final int FRAME_WIDTH = 300;

     14     private static final int FRAME_HEIGHT = 400;

     15

     16     private JPanel colorPanel;

     17     private JSlider redSlider;

     18     private JSlider greenSlider;

     19     private JSlider blueSlider;

     20

     21     public ColorFrame()

     22     {

     23        colorPanel = new JPanel();

     24

     25        add(colorPanel, BorderLayout.CENTER);

     26        createControlPanel();

     27        setSampleColor();

     28        setSize(FRAME_WIDTH, FRAME_HEIGHT);

     29     }

     30

     31     class ColorListener implements ChangeListener

     32     {

     33        public void stateChanged(ChangeEvent event)

     34        {

     35           setSampleColor();

     36        }

     37     }

     38

     39     public void createControlPanel()

     40     {

     41        ChangeListener listener = new ColorListener();

     42

     43        redSlider = new JSlider(0, 255, 255);

     44        redSlider.addChangeListener(listener);

     45

     46        greenSlider = new JSlider(0, 255, 175);

     47        greenSlider.addChangeListener(listener);

     48

     49        blueSlider = new JSlider(0, 255, 175);

     50        blueSlider.addChangeListener(listener);

     51

     52        JPanel controlPanel = new JPanel();

     53        controlPanel.setLayout(new GridLayout(3, 2));

     54

     55        controlPanel.add(new JLabel("Red"));

     56        controlPanel.add(redSlider);

     57

     58        controlPanel.add(new JLabel("Green"));

     59        controlPanel.add(greenSlider);

     60

     61        controlPanel.add(new JLabel("Blue"));

     62        controlPanel.add(blueSlider);

     63

     64        add(controlPanel, BorderLayout.SOUTH);

     65     }

     66

     67     /**

     68        Reads the slider values and sets the panel to

     69        the selected color.

     70     */

     71     public void setSampleColor()

     72     {

     73        // Read slider values

     74

     75        int red = redSlider.getValue();

     76        int green = greenSlider.getValue();

     77        int blue = blueSlider.getValue();

     78

     79        // Set panel background to selected color

     80

     81        colorPanel.setBackground(new Color(red, green, blue));

     82        colorPanel.repaint();

     83     }

     84  }